const defaultAvatarUrl = 'https://mmbiz.qpic.cn/mmbiz/icTdbqWNOwNRna42FI242Lcia07jQodd2FJGIYQfG0LAJGFxM4FbnQP6yfMxBgJ0F3YRqJCJ1aPAK2dQagdusBZg/0'

Page({
  data: {
    userInfo: {
      avatarUrl: defaultAvatarUrl,
      Nickname: '',
    },
    hasUserInfo: false,
    canIUseGetUserProfile: wx.canIUse('getUserProfile'),
    canIUseNicknameComp: wx.canIUse('input.type.nickname'),
  },

  // 页面跳转函数
  bindViewTap() {
    wx.navigateTo({
      url: '../logs/logs'
    })
  },

  // 选择头像后的处理函数
  onChooseAvatar(e) {
    const {
      avatarUrl
    } = e.detail
    const {
      nickName
    } = this.data.userInfo
    this.setData({
      "userInfo.avatarUrl": avatarUrl,
      hasUserInfo: nickName && avatarUrl && avatarUrl !== defaultAvatarUrl,
    })
    // 存储头像
    wx.setStorageSync('avatarUrl', avatarUrl)
  },

  // 输入昵称变化后的处理函数
  onInputChange(e) {
    const nickName = e.detail.value
    const {
      avatarUrl
    } = this.data.userInfo
    this.setData({
      "userInfo.nickName": nickName,
      hasUserInfo: nickName && avatarUrl && avatarUrl !== defaultAvatarUrl,
    })
    // 存储昵称
    wx.setStorageSync('nickName', nickName)
  },

  getUserProfile(e) {
    // 推荐使用wx.getUserProfile获取用户信息，开发者每次通过该接口获取用户个人信息均需用户确认，开发者妥善保管用户快速填写的头像昵称，避免重复弹窗
    wx.getUserProfile({
      desc: '展示用户信息', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
      success: (res) => {
        console.log(res)
        this.setData({
          userInfo: res.userInfo,
          hasUserInfo: true
        })
      }
    })
  },

  // 登录函数
  login() {
    // 检查是否有头像和昵称
    const {
      userInfo,
      hasUserInfo
    } = this.data;
    if (!hasUserInfo) {
      wx.showToast({
        title: '请完善头像和昵称',
        icon: 'none',
      });
      return;
    }
    const app = getApp();
    wx.login({
      success: (res) => {
        if (res.code) {
          console.log(res.code)
          wx.request({
            url: `${app.globalData.baseUrl}/user/login`, // 确保 URL 正确
            method: 'POST',
            data: {
              code: res.code,
              avatarUrl: userInfo.avatarUrl,
              nickName: userInfo.nickName
            },
            success: (response) => {
              console.log(response);
              if (response.statusCode === 200) {
                const openid = response.data.data.openid;
                const token = response.data.data.token;
                const id = response.data.data.id;
                // 存储 openid 和 token 到本地存储
                wx.setStorageSync('openid', openid);
                wx.setStorageSync('token', token);
                wx.setStorageSync('id', id);
                console.log(openid);
                console.log(token);
                // 登录成功后跳转到首页
                wx.switchTab({
                  url: '/pages/home/home'
                });
              } else {
                console.error('发送 code 给后端失败:', response.statusCode);
              }
            },
            fail: (err) => {
              console.error('请求后端失败:', err);
              wx.showToast({
                title: '网络请求失败，请检查网络设置',
                icon: 'none',
              });
            }
          });
        } else {
          console.error('登录获取 code 失败:', res.errMsg);
        }
      },
      fail: (err) => {
        console.error('登录失败:', err);
      }
    });
  }
})